package com.jron.cqiu.kernel.implement;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.Email;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.mail.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.io.*;

import com.jron.cqiu.kernel.util.SystemProperties;
import com.jron.cqiu.kernel.mail.ReceiveType;
import com.jron.cqiu.util.ConfigurationUtil;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-17
 * @Time: 9:22:52
 */
public class PraseMimeMessage {

    private static Log log = LogFactory.getLog(PraseMimeMessage.class);

    private MimeMessage mimeMessage = null;
    private String saveAttachPath = null; // 附件下载后的存放目录
    private StringBuffer bodytext = new StringBuffer(); // 存放邮件内容的StringBuffer对象
    private String dateformat = "yy-MM-dd HH:mm:ss";

    private String encoding = "gb2312";

    public PraseMimeMessage() {
    }

    public PraseMimeMessage(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
        log.debug("create a PraseMimeMessage object..");
    }

    public void setMimeMessage(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }

    /**
     * 获得发件人的地址和姓名
     *
     * @return
     * @throws Exception
     */
    public String getFrom() throws Exception {
        InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
        String from = address[0].getAddress();
        if (StringUtils.isBlank(from)) from = "";

        String personal = address[0].getPersonal();
        if (StringUtils.isBlank(personal)) personal = "";

        return personal + "<" + from + ">";
    }

    /**
     * 获得邮件的收件人，抄送，和密送的地址和姓名，根据所传递的参数的不同
     * "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
     *
     * @param type
     * @return
     * @throws Exception
     */
    public String getMailAddress(ReceiveType type) throws Exception {
        String mailaddr = "";
        InternetAddress[] address = null;

        switch (type) {
            case TO:
                address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
                break;
            case CC:
                address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
                break;
            case BCC:
                address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
                break;
            default:
                throw new Exception("Error emailaddr type!");
        }

        if (address != null) {
            for (InternetAddress addres : address) {
                String email = addres.getAddress();
                email = (email == null ? "" : MimeUtility.decodeText(email));

                String personal = addres.getPersonal();
                personal = (personal == null ? "" : MimeUtility.decodeText(personal));

                String compositeto = personal + "<" + email + ">";
                mailaddr += "," + compositeto;
            }
            mailaddr = mailaddr.substring(1);
        }
        return mailaddr;
    }

    /**
     * 获得邮件主题
     *
     * @return
     * @throws MessagingException
     */
    public String getSubject() throws MessagingException {
        String subject = "";
        try {
            subject = MimeUtility.decodeText(mimeMessage.getSubject());
            if (StringUtils.isBlank(subject)) subject = "";
        } catch (Exception exce) {
            exce.printStackTrace();
        }
        return subject;
    }

    /**
     * 获得邮件发送日期
     *
     * @return
     * @throws Exception
     */
    public String getSentDate() throws Exception {
        Date sentdate = mimeMessage.getSentDate();
        SimpleDateFormat format = new SimpleDateFormat(dateformat);
        return format.format(sentdate);
    }

    /**
     * 获得邮件正文内容
     *
     * @return
     */
    public String getBodyText() {
        return bodytext.toString();
    }

    /**
     * 解析邮件，把得到的邮件内容保存到一个StringBuffer对象中，
     * 解析邮件 主要是根据MimeType类型的不同执行不同的操作，一步一步的解析
     *
     * @param part
     * @throws Exception
     */
    public void getMailContent(Part part) throws Exception {
        String contenttype = part.getContentType();
        int nameindex = contenttype.indexOf("name");
        boolean conname = false;
        if (nameindex != -1) conname = true;

        log.debug("content type: " + contenttype);

        if (part.isMimeType(Email.TEXT_PLAIN) && !conname) {
            bodytext.append((String) part.getContent());
        } else if (part.isMimeType(Email.TEXT_HTML) && !conname) {
            bodytext.append((String) part.getContent());
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) getMailContent(multipart.getBodyPart(i));
        } else if (part.isMimeType("message/rfc822")) {
            getMailContent((Part) part.getContent());
        } else {
        }
    }

    /**
     * 判断此邮件是否需要回执，如果需要回执返回"true",否则返回"false"
     *
     * @return
     * @throws MessagingException
     */
    public boolean getReplySign() throws MessagingException {
        boolean replysign = false;
        String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
        if (needreply != null) replysign = true;
        return replysign;
    }

    /**
     * 获得此邮件的Message-ID
     *
     * @return
     * @throws MessagingException
     */
    public String getMessageId() throws MessagingException {
        return mimeMessage.getMessageID();
    }

    /**
     * 【判断此邮件是否已读，如果未读返回返回false,反之返回true】
     *
     * @return
     * @throws MessagingException
     */
    public boolean isNew() throws MessagingException {
        boolean isnew = false;
        Flags flags = mimeMessage.getFlags();
        Flags.Flag[] flag = flags.getSystemFlags();
        log.debug("flags's length: " + flag.length);
        for (Flags.Flag aFlag : flag) {
            if (aFlag == Flags.Flag.SEEN) {
                isnew = true;
                log.debug("seen Message.");
                break;
            }
        }
        return isnew;
    }

    /**
     * 判断此邮件是否包含附件
     *
     * @param part
     * @return
     * @throws Exception
     */
    public boolean isContainAttach(Part part) throws Exception {
        boolean attachflag = false;
        //String contentType = part.getContentType();
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if ((disposition != null)
                        && ((disposition.equals(Part.ATTACHMENT))
                        || (disposition.equals(Part.INLINE))))
                    attachflag = true;
                else if (mpart.isMimeType("multipart/*")) {
                    attachflag = isContainAttach(mpart);
                } else {
                    String contype = mpart.getContentType();
                    if (contype.toLowerCase().indexOf("application") != -1)
                        attachflag = true;
                    if (contype.toLowerCase().indexOf("name") != -1)
                        attachflag = true;
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            attachflag = isContainAttach((Part) part.getContent());
        }
        return attachflag;
    }

    /**
     * 【保存附件】
     *
     * @param part
     * @throws Exception
     */
    public void saveAttachMent(Part part) throws Exception {
        String fileName = "";
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if ((disposition != null)
                        && ((disposition.equals(Part.ATTACHMENT)) || (disposition
                        .equals(Part.INLINE)))) {
                    //fileName = mpart.getFileName();
                    fileName = getISOFileName(mpart);
                    if (StringUtils.isNotBlank(fileName) && fileName.toLowerCase().indexOf(encoding) != -1) {
                        fileName = MimeUtility.decodeText(fileName);
                    }
                    if (StringUtils.isNotBlank(fileName)) saveFile(fileName, mpart.getInputStream());
                } else if (mpart.isMimeType("multipart/*")) {
                    saveAttachMent(mpart);
                } else {
                    //fileName = mpart.getFileName();
                    fileName = getISOFileName(mpart);
                    if (StringUtils.isNotBlank(fileName) && (fileName.toLowerCase().indexOf(encoding) != -1)) {
                        fileName = MimeUtility.decodeText(fileName);
                        saveFile(fileName, mpart.getInputStream());
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachMent((Part) part.getContent());
        }
    }

    /**
     * 从BodyPart中提取使用ISO-8859-1编吗的文件名 因为BodyPart.getFilename()过程已经对文件名作了一次编码，有时不能直接使用
     *
     * @param body
     * @return
     */
    public static String getISOFileName(Part body) {
        //设置一个标志，判断文件名从Content-Disposition中获取还是从Content-Type中获取
        boolean flag = true;
        if (body == null) return null;
        String[] cdis;
        try {
            cdis = body.getHeader("Content-Disposition");
        } catch (Exception e) {
            return null;
        }
        if (cdis == null) flag = false;
        if (!flag) {
            try {
                cdis = body.getHeader("Content-Type");
            } catch (Exception e) {
                return null;
            }
        }
        if (cdis == null) return null;
        if (cdis[0] == null) return null;
        //从Content-Disposition中获取文件名
        if (flag) {
            int pos = cdis[0].indexOf("filename=");
            if (pos < 0) return null;
            //如果文件名带引号
            if (cdis[0].charAt(cdis[0].length() - 1) == '"') return cdis[0].substring(pos + 10, cdis[0].length() - 1);
            return cdis[0].substring(pos + 9, cdis[0].length());
        } else {
            int pos = cdis[0].indexOf("name=");
            if (pos < 0) return null;
            //如果文件名带引号
            if (cdis[0].charAt(cdis[0].length() - 1) == '"') return cdis[0].substring(pos + 6, cdis[0].length() - 1);
            return cdis[0].substring(pos + 5, cdis[0].length());
        }
    }

    /**
     * 【设置附件存放路径】
     *
     * @param attachpath
     */
    public void setAttachPath(String attachpath) {
        this.saveAttachPath = attachpath;
    }

    /**
     * 【设置日期显示格式】
     *
     * @param format
     * @throws Exception
     */
    public void setDateFormat(String format) throws Exception {
        this.dateformat = format;
    }

    /**
     * 【获得附件存放路径】
     *
     * @return
     */
    public String getAttachPath() {
        return saveAttachPath;
    }

    /**
     * 【真正的保存附件到指定目录里】
     *
     * @param fileName
     * @param in
     * @throws Exception
     */

    private void saveFile(String fileName, InputStream in) throws Exception {
        String storedir = getAttachPath();
        String separator = "";

        switch (SystemProperties.SYSTEM) {
            case WINDOWS:
                separator = "\\";
                if (StringUtils.isBlank(storedir))
                    storedir = ConfigurationUtil.value("mail.default.attachment.saveto");
                break;
            default:
                separator = "/";
                storedir = "/tmp";
                break;
        }

        File storefile = new File(storedir + separator + fileName);
        log.debug("Storefile's path: " + storefile.toString());

        // for(int i=0;storefile.exists();i++){
        // storefile = new File(storedir+separator+fileName+i);
        // }
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(storefile));
            bis = new BufferedInputStream(in);
            int c;
            while ((c = bis.read()) != -1) {
                bos.write(c);
                bos.flush();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new Exception("File save failed! " + exception.getMessage());
        } finally {
            bos.close();
            bis.close();
        }
    }

    protected static String decodeText(String text)
            throws UnsupportedEncodingException {
        if (text == null)
            return null;
        if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
        else
            text = new String(text.getBytes("ISO8859_1"));
        return text;
    }

}
